import logging
import base64
import configparser
from Download import *
from Login import *
from danmaku2ass import *

# 当前版本号
VER = "0.95"

if __name__ == '__main__':
    # 日志相关配置
    LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
    DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p"
    if not os.path.exists("./Log"):
        logging.info("创建目录:" + "./Log")
        os.makedirs("./Log")
    logging.basicConfig(filename="Log/system.log", level=logging.INFO, format=LOG_FORMAT, datefmt=DATE_FORMAT)
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    formatter = logging.Formatter(LOG_FORMAT)
    console.setFormatter(formatter)
    logging.getLogger('').addHandler(console)
    # 读取配置信息
    if not os.path.exists("config.ini"):
        logging.info("创建文件:" + "config.ini")
        with open("config.ini", "w") as fp:
            fp.write("[info]\nnum_thread = 10\nneedlogin = 1\ncookie =")
    conf = configparser.ConfigParser()
    conf.read("config.ini", encoding="utf-8")
    num_thread = int(conf.get("info", "num_thread"))
    cookie = conf.get("info", "cookie")
    cookie = base64.b64decode(cookie).decode("utf-8")
    needLogin = conf.get("info", "needLogin")
    # 主流程
    print("===============================================")
    print("BiliBili视频下载程序 -v " + VER + " -by NC 2021-1-1")
    print("===============================================")

    while True:
        referer = input("请输入需要下载的视频页面：")
        print("当前需要处理的路径为: ", referer)

        # 检测登录状态
        logging.info("===============================================")
        logging.info("预处理")
        logging.info("===============================================")
        if needLogin == "1":
            loginState = checkLogin(cookie)
            if loginState is False:
                logging.info("检测到未登录，请使用BiliBili手机客户端扫码登陆！")
                loginUrl, oauthKey = getLoginUrl()
                createQrcode(loginUrl)
                cookiesDict = viewQrcode(oauthKey)
                cookieStr = cookie2Str(cookiesDict)
                cookie = cookieStr
                bytes_cookieStr = cookieStr.encode("utf-8")
                base64_cookieStr = base64.b64encode(bytes_cookieStr)
                conf.set("info", "cookie", str(base64_cookieStr)[2:-1])
                with open('config.ini', 'w') as f:
                    conf.write(f)
            else:
                logging.info("检测到账号已登录！")

        # 获取主页面max信息
        state, info, bvid, cid, width, height, part, size, url = mainPageAnalysis(referer, cookie)
        if state is False:
            logging.error(info)
            continue

        logging.info("===============================================")
        logging.info(bvid + " - " + part)
        logging.info("===============================================")
        logging.info("下载开始...")
        # 下载视频文件
        downloadVideo(referer, url, size, num_thread, "./temp/" + bvid, part + ".flv")
        # 下载弹幕文件
        downloadDanmu(cid, cookie, "./temp/" + bvid, part + ".xml")
        Danmaku2ASS("./temp/" + bvid + "/" + part + ".xml", 'autodetect', "./temp/" + bvid + "/" + part + ".ass", width, height, duration_marquee=15)
        # 打开文件夹
        truePath = os.path.split(os.path.realpath(__file__))[0]
        display_file = truePath + "\\temp\\" + bvid + "\\" + part + ".flv"
        os.system(r'explorer /select,"' + display_file + '"')

        logging.info("下载完成！")
        logging.info("===============================================")
        logging.info("")
        logging.info("")
        print("")
        print("")
        print("===============================================")
        print(bvid + " - " + part + "处理完成！")
        print("===============================================")
        print("")
        print("")
